package com.xd.client;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: 薛 棣
 * @Date :2020/2/2
 * @Type: com.xd.client}
 * @function: 分布式节点挂载中心
 */
public class ZookeeperNodeConfig implements Watcher {

    //条件触发器
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    //客户端
    private static ZooKeeper zooKeeper = null;

    //监听的zk节点状态
    private static Stat status = new Stat();

    /**
     * @Author: 薛 棣
     * @param path zk挂载节点路径
     */
    public static void doListener(String path) throws IOException, InterruptedException, KeeperException {
        //初始化客户端
        zooKeeper = new ZooKeeper("192.168.127.133:2181",3000,new ZookeeperNodeConfig());
        //等待连接
        countDownLatch.await();
        //连接成功
        byte[] data = zooKeeper.getData(path, true, status);
        //输出节点信息
        System.out.println("当前节点配置信息为:"+new String(data));
        Thread.sleep(Integer.MAX_VALUE);
    }

    //节点信息回调通知处理Method
    @Override
    public void process(WatchedEvent watchedEvent) {
        if (Event.KeeperState.SyncConnected == watchedEvent.getState()){
            //zk连接成功
            if (Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()){
                //连接成功,节点挂载数据未变化
                countDownLatch.countDown();
            }else if (watchedEvent.getType() == Event.EventType.NodeDataChanged){
                //节点数据发生变化
                try {
                    zooKeeper = new ZooKeeper("192.168.127.133:2181", 3000, new ZookeeperNodeConfig());
                    System.out.println("节点挂载数据发生了变化:"+ new String(zooKeeper.getData(watchedEvent.getPath(),true,status)) );
                } catch (Exception e) {
                    System.out.println("远程客户端节点连接异常,原因是:"+e.getMessage());
                }
            }
        }

    }

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException{
        doListener("/config-no");
    }
}
